import { useState, useEffect, useRef } from 'react'
import { DateInfo, getCurrentDateInfo } from '@/utils/time.ts'
import { _getAssets } from '@/utils/assets.ts'
import indexStyle from './Index.module.scss'
import { ThreeModel } from '@/hooks/threejs.tsx'

function Index() {
  // 使用 useState 创建响应式状态 currentTimeInfo
  const [currentTimeInfo, setCurrentTimeInfo] = useState<DateInfo | null>(null)

  const intervalRef = useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    // 获取当前的时间信息并设置到 state 中
    intervalRef.current = setInterval(() => {
      const timeInfo = getCurrentDateInfo()
      setCurrentTimeInfo(timeInfo)
    }, 1000)

    setCommonBg()

    return () => {
      console.log('Timer cleared')
      clearInterval(intervalRef.current as any)
    }
  }, []) // 依赖数组为空，只会在组件挂载时执行一次

  const setCommonBg = () => {
    const bgList = ['bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg']
    const randomIndex = Math.floor(Math.random() * bgList.length)
    // --common-bg,用_getAssets传入文件名
    document.documentElement.style.setProperty(
      '--common-bg',
      `url(${_getAssets(bgList[randomIndex], 'bg')}` + ')'
    )
  }

  return (
    <div className={indexStyle.index}>
      <div className={indexStyle.hello}>{currentTimeInfo?.amOrPm}好，欢迎光临</div>

      <div className={indexStyle.timeContainer}>
        <div className={indexStyle.time}>
          <span className={indexStyle.num}>{currentTimeInfo?.time.hours}</span>
          <span className={indexStyle.separator}>:</span>
          <span className={indexStyle.num}>{currentTimeInfo?.time.minutes}</span>
          <span className={indexStyle.separator}>:</span>
          <span className={indexStyle.num}>{currentTimeInfo?.time.seconds}</span>
        </div>
        <span className={indexStyle.lunar}>
          {currentTimeInfo?.lunarDate.yearName}年 {currentTimeInfo?.lunarDate.monthName}月
          {currentTimeInfo?.lunarDate.dayName}
        </span>
        <span className={indexStyle.monDayWeek}>
          {currentTimeInfo?.gregorianDate.month}月{currentTimeInfo?.gregorianDate.day}日
          {currentTimeInfo?.weekday}
        </span>
      </div>

      <div className={indexStyle.banner}>
        <ThreeModel></ThreeModel>
      </div>
      <span className={indexStyle.copyright}>2024 Fate. All Rights Reserved.</span>
    </div>
  )
}

export default Index
